<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      img {
        width: 40px;
        /* height: 80px; */
      }
    </style>
  </head>
  <body>
    <div class="img"></div>
    <script>
      window.onload = function () {
        var div = document.querySelector("div.img");
        //构造函数
        var TrafficLight = function () {
          // 给函数对象定义初始值
          this.color = 1;
          this.dom = null;
          // 给对象内容初始化
          this.init();
        };
        //初始化函数 init()
        TrafficLight.prototype.init = function () {
          this.dom = document.createElement("img");
          this.dom.src = "./img/" + this.color + ".jpg";
          div.appendChild(this.dom);
          this.bindEvent();
        };

        //绑定事件 bindEvent()
        TrafficLight.prototype.bindEvent = function () {
          //切换颜色
          this.changeColor();
        };
        //切换颜色 changeColor()
        TrafficLight.prototype.changeColor = function () {
          var that;
          that = this;
          this.dom.onclick = function () {
            // alert(that.color);
            that.color++;
            if (that.color == 4) {
              that.color = 1;
            }
            this.src = "./img/" + that.color + ".jpg";
          };
        };
        // 创建100个实例对象
        for (let i = 0; i < 100; i++) {
          new TrafficLight();
        }
      };
    </script>
  </body>
</html>
